package org.project3;

import org.project3.annotations.Constraints;
import org.project3.annotations.DBtable;
import org.project3.annotations.SQLType;


import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;



public class CreatorTable {
    public static void run( Class<?> cls) {
        String tableName="";

        // 获取类上的所有注解
        Annotation[] classAnnotations = cls.getAnnotations();
        for (Annotation annotation : classAnnotations) {
            if (annotation instanceof DBtable) {
                DBtable dbTable = (DBtable) annotation;
                tableName=dbTable.name();
                System.out.println("Table name: " + tableName);
            }
        }
        // 获取类的所有字段
        Field[] fs = cls.getDeclaredFields();
        StringBuilder columns = new StringBuilder();
        for (Field f : fs) {
            System.out.println("Field name: " + f.getName());
            // 获取字段上的所有注解
            Annotation[] fieldAnnotations = f.getAnnotations();
            for (Annotation annotation : fieldAnnotations) {
                if (annotation instanceof SQLType) {
                    SQLType sqlType = (SQLType) annotation;
                    String dbtype = sqlType.dbtype();
                    Constraints constraints = sqlType.constraints();
                    // 构建字段定义
                    if (columns.length() > 0) {
                        columns.append(", ");
                    }
                    columns.append(f.getName()).append(" ").append(dbtype);
                    if (constraints != null && constraints.primaryKey()) {
                        columns.append(" PRIMARY KEY");
                    }
                    // 可根据 Constraints 类添加更多约束条件
                    System.out.println(constraints);
                }
            }
        }
        if (columns.length() == 0) {
            System.err.println("未找到有效的字段信息，无法创建表。");
            return;
        }
        System.out.println("Columns: " + columns.toString());
        String sql = "CREATE TABLE " + tableName + " (" + columns.toString() + ")";
        System.out.println("Generated SQL: " + sql);
        // 连接数据库
        try (
                Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/HRPDB", "hr", "a");
                Statement stmt = conn.createStatement()
        ) {
            stmt.executeUpdate(sql);
            System.out.println("表创建成功。");
        } catch (SQLException ex) {
            // 使用日志记录异常，而不是 printStackTrace
            System.err.println("表创建失败: " + ex.getMessage());
        }
    }
}
